package com.alibaba.user.service;


import com.alibaba.api.pojos.Account;
import com.alibaba.api.pojos.User;
import com.alibaba.api.service.UserServiceApi;
import com.alibaba.user.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.RandomUtils;
import org.apache.dubbo.config.annotation.Service;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.util.DigestUtils;
import org.springframework.web.client.RestTemplate;

import java.time.Duration;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service(version = "1.0.0")
public class UserServiceImpl  implements UserServiceApi {

    @Autowired
    private UserMapper userMapper;

    @Value("jwt.secret")
    private String secret;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public boolean register(User user) {

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", user.getPhone());

        User u = userMapper.selectOne(wrapper);

        if (null != u) {
            return false;
        }
        user.setCreateTime(new Date());
        user.setAccountId(new Date().getTime());

        try {
            Account account = new Account();
            account.setAccountId(user.getAccountId());
            account.setCreateTime(user.getCreateTime());
            account.setUpdateTime(user.getCreateTime());
            account.setBalance(0);
            account.setAccountName(user.getUsername());
            insert(account);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return userMapper.insert(user) == 1;
    }

    @Override
    public Map<String, String> login(String phone) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", phone);
        User user = userMapper.selectOne(wrapper);
        if (null == user) {
            //新用户
            User u = new User();
            u.setUsername(phone);
            u.setPhone(phone);
            u.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
            register(user);

        }
        String token = getToken(user.getId(), user.getAccountId());
        Map map = new HashMap<>();
        map.put("token", token);
        return map;
    }

    @Override
    public Map<String, String> code(String phone) {
        Integer code = RandomUtils.nextInt(100000, 999999);
        redisTemplate.boundValueOps(phone).set(code.toString(), Duration.ofMinutes(5));

        Map map = new HashMap();
        map.put("code", code);
        return map;
    }

    private String getToken(Integer id, Long accountId) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", id);
        claims.put("accountId", accountId);
        String token = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS256, "secret")
                .setExpiration(new DateTime().plusHours(12).toDate())
                .compact();
        return token;
    }


    public void insert(Account account) {
        account.setCreateTime(new Date());
        account.setUpdateTime(new Date());
        String url = "http://localhost/web//register/account";
        HttpEntity httpEntity = new HttpEntity(account);
        restTemplate.postForEntity(url, httpEntity, String.class);
    }
}
